﻿using Batman.Cms.Core.Extensions;
using Batman.Cms.Core.Models.Consul;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace Batman.Cms.Core.Consul
{
    public static class ConsulResiter
    {
        /// <summary>
        ///  注册本系统到consul服务中
        /// </summary>
        /// <param name="services"></param>
        public static void TryResiterConsul(this IServiceCollection services)
        {
            var env = services.BuildServiceProvider().GetService<IHostingEnvironment>();
            var applicationInfo = env.GetApplicationInfo();
            var consulUrl = env.GetConsulUrl();

            ConsulServiceModel model = new ConsulServiceModel();
            model.ID = applicationInfo.Id;
            model.Name = applicationInfo.Name;
            model.Address = applicationInfo.Address;
            model.Port = applicationInfo.Port;
            model.Tags = new List<string> { "normal" }; // 


            model.Check = new ConsulHealthCheckInfo
            {
                HTTP = applicationInfo.GetUrl() + "/Consul/Health",
                Interval = "30s", // 默认三十秒检查
                DeregisterCriticalServiceAfter = "90m"
            };

            try
            {
                // todo: 目前这种方式，第一次都是不健康的，要过三十秒后第二次consul检查后才能变成安全
                using (var client = new WebClient())
                {
                    var api = $"{consulUrl}/v1/agent/service/register";
                    var json = JsonConvert.SerializeObject(model);
                    var data = Encoding.UTF8.GetBytes(json);
                    client.UploadData(api, "PUT", data); // 用Put方法请求数据
                    // todo: 判断返回是否正确，并写日志
                }
            }
            catch (Exception)
            {
                // todo: 写日志
            }
        }
    }
}
